import fs from 'node:fs';
import path from 'path';
import { AppName } from '../app.config.js';
/*
  数据封装
 */
class fantasyData {
  constructor() {
    //获取配置文件参数
    
    //文件路径参数
    //插件根目录
    const __dirname =
      path.resolve() + path.sep + 'plugins' + path.sep + AppName;
    this.filePathMap = {
      player: path.join(__dirname, '/resources/data/player'), //用户数据
      equipment: path.join(__dirname, '/resources/data/equipment'),
      bag: path.join(__dirname, '/resources/data/bag'),
      lib: path.join(__dirname, '/resources/data/lib'),
      map: path.join(__dirname, '/resources/data/map'),
      data: path.join(__dirname, '/resources/data'),
    };
    this.lib_path = this.filePathMap.lib;
    //加载列表
    this.talent_list = JSON.parse(
      fs.readFileSync(`${this.lib_path}/天赋列表.json`)
    );

    //加载等级列表
    this.level_list = JSON.parse(
      fs.readFileSync(`${this.lib_path}/等级列表.json`)
    );
    }
    /**
   * 检测存档存在
   * @param file_path_type ["player" , "association" ]
   * @param file_name
   */
  existData(file_path_type, file_name) {
    let file_path;
    file_path = this.filePathMap[file_path_type];
    let dir = path.join(file_path + '/' + file_name + '.json');
    if (fs.existsSync(dir)) {
      return true;
    }
    return false;
  }

  /**
   * 获取文件数据(user_qq为空查询item下的file_name文件)
   * @param file_name  [player,equipment,najie]
   * @param user_qq
   */
  getData(file_name, user_qq) {
    let file_path;
    let dir;
    let data;
    if (user_qq) {
      //带user_qq的查询数据文件
      file_path = this.filePathMap[file_name];
      dir = path.join(file_path + '/' + user_qq + '.json');
    } else {
      //不带参数的查询item下文件
      file_path = this.filePathMap.lib;
      dir = path.join(file_path + '/' + file_name + '.json');
    }
    try {
      data = fs.readFileSync(dir, 'utf8');
    } catch (error) {
      logger.error('读取文件错误：' + error);
      return 'error';
    }
    //将字符串数据转变成json格式
    data = JSON.parse(data);
    return data;
  }

  /**
   * 写入数据
   * @param file_name [player,equipment,najie]
   * @param user_qq
   * @param data
   */
  setData(file_name, user_qq, data) {
    let file_path;
    let dir;
    if (user_qq) {
      file_path = this.filePathMap[file_name];
      dir = path.join(file_path + '/' + user_qq + '.json');
    } else {
      file_path = this.filePathMap.lib;
      dir = path.join(file_path + '/' + file_name + '.json');
    }
    let new_ARR = JSON.stringify(data, '', '\t'); //json转string
    if (fs.existsSync(dir)) {
      fs.writeFileSync(dir, new_ARR, 'utf-8', err => {
        console.log('写入成功', err);
      });
    }
    return;
  }
  }
    export default new fantasyData();